package com.zhdl.network.demotcp.conf;

import com.project.network.client.SerialSocketClient;
import com.project.network.conf.LinkClientSocketBuild;
import com.project.network.entity.PortSocket;
import com.zhdl.network.demotcp.analysis.MemoBusTcpListener;
import com.zhdl.network.demotcp.dto.MemoBusPacket;
import com.zhdl.network.modbustcp.analysis.ModBusTcpClientHandler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

@Slf4j
@Component
public class ModbusClientSocketBuild extends LinkClientSocketBuild {
    @Override
    protected SerialSocketClient buildMemoBusClient(PortSocket properties) {
        return null;
    }

    @Override
    protected SerialSocketClient buildModBusClient(PortSocket properties) {
        return null;
    }

    @Override
    protected SerialSocketClient buildModBusTcpClient(PortSocket properties) {
        return buildClient(properties);
    }

    protected SerialSocketClient buildClient(PortSocket properties) {
        String port = properties.getClientPort();
        String clientIp = properties.getClientIp();
        String protocols = properties.getProtocols();
        String serverIp = properties.getServerIp();
        String serverPort = properties.getServerPort();
        Integer timeouts = properties.getTimeouts();

//        MemoBusTcpClientHandler handler = new MemoBusTcpClientHandler(serverIp, serverPort, protocols, message);
        ModBusTcpClientHandler handler = new ModBusTcpClientHandler(serverIp, serverPort, protocols, message);
        MemoBusTcpListener listener = new MemoBusTcpListener();
        MemoBusPacket packet = new MemoBusPacket();
        Integer clientPort = Integer.parseInt(port);

        // 这边可以根据启动环境，重新修改连接配置信息
//        String envType = environment.getActiveProfiles()[0];
//        if ("dev".equals(envType)) {
//            // 由于前后机本地端口一样，所以为了能同时使用，后机加10010，具体见电机本地地址分配表
//            if (clientIp.equals("192.168.1.110")) {
//                clientPort += (10000 + 10);
//            } else {
//                clientPort += 10;
//            }
//            serverIp = "127.0.0.1";
//            clientIp = "127.0.0.1";
//        }
        // 那这边你可以判断是127的话加下对应的业务逻辑判断，就使用不同端口，要不启动不起来

        SerialSocketClient socket = new SerialSocketClient(handler, listener, packet, serverIp, serverPort, port, clientIp, clientPort, timeouts);
        try {
            socket.openSocket();
        } catch (Exception e) {
            throw exceptionBuild.newException("9999", e);
        }
        return socket;
    }
}
